package com.demo.rbactest.controller;

import com.demo.rbactest.entity.User;
import com.demo.rbactest.model.LoginR;
import com.demo.rbactest.model.R;
import com.demo.rbactest.service.UserService;
import com.demo.rbactest.utils.TokenTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@RestController
public class UserController {
    final
    UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    //    用户登录
    @PostMapping("login")
    public LoginR login(User user) {
//        先通过账号密码获取数据库中的用户信息
        final User one = userService.getOne(user);
        if (one == null) {
            throw new RuntimeException("用户名或者密码错误");
        }
//        获取用户权限
        final List<String> permissions = userService.getPermissions(one.getRole());
//        生成token
        final String token = TokenTool.create(user);
        return LoginR.success(permissions, token);
    }

    //    用户注册
    @PostMapping("register")
    public R register(User user) {
        final Integer save = userService.save(user);
        if (save == 0) {
            throw new RuntimeException("该用户已经注册过了");
        }
        return R.success("注册成功");
    }

}
